<?php
namespace app\api\controller;
/**
 * User: huangzhen
 * Date: 2021/06/17
 */

use app\common\model\CardsTransCredit;
use app\common\model\ManageLog;
use app\common\model\UserCashLog;
use app\common\model\UserLog;
use app\common\model\UserSet;
use think\facade\Db;
use app\common\model\Cards as cardsModel;
use app\common\model\User as userModel;
use think\facade\Request;
use think\facade\Cache;

class Timer
{

    public function __construct()
    {
        $params = Request::param();
        if(empty($params)){
            exit('Welcome to BetterEpay');
        }else{
            $token = $params['token'];
            //4ba0229e63c4a0ec6ba5e999cba5d586
            if($token !=md5(md5('BetterEpay') . md5(2022))){
                exit('Welcome to BetterEpay !');
            }
        }
    }
    public function index()
    {
        exit('Welcome to BetterEpay 2022 !');
    }

    public function upUserData()
    {
        $start  = getUtcTime();
        $model  = new userModel();
        $re     = $model->updataUserData();
        $end    = getUtcTime();
        echo 'time : ' . ($end - $start) . ' ; result:' . json_encode($re);

    }

    /**
     * 新建卡，每一分钟更新卡信息，获取完整卡号CVV
     */
    public function upCardData()
    {
        $cdModel   = new cardsModel();
        $time      = getUtcTime();
        $list = Db::name('cards')->where('check_status=0')
            ->limit(10)->select()->toArray();
        if(!empty($list)){
            $cdModel->updateCard($time);
            echo 'success';
        }else{
            echo 'list is null';
        }
    }

    public function upCardBalance()
    {
        $card_list  = Db::name('cards')->select()->toArray();
        $start_time = getUtcTime();
        foreach ($card_list as $v){
            $card_num   = $v['card_num'];
            $card_id    = $v['id'];
            $card_type  = $v['card_type'];
            $user_id    = $v['user_id'];
            $card_status= $v['status'];
            $balance_account    = $v['balance_account'];
            $send_param         = [
                "user_id"       => $user_id,
                "action_type"   => "searchExpDate2",
                "card_type"     => $card_type,
                "post_param"    => [
                    "card_num"  => $card_num,
                ]
            ];
            $check_card_api = PublicApi::requestApi('Comdata',$send_param);
            $return_blog    = $check_card_api['blog'];
            $return_list    = $check_card_api['list'];
            if($return_blog) {
                $api_amount = $return_list['cycleAmountLimitAvailable'];
                $api_amount_total = $return_list['cycleAmountLimit'];
                if($api_amount_total - $balance_account != 0){
                    $error_data_param =json_encode(['card_num'=>$card_num]);
                    $api_error_list = Db::name('api_error')
                        ->where(['data_param'=>$error_data_param])->find();
                    if(empty($api_error_list)){
                        Db::name('api_error')->save([
                            'user_id'       => $user_id,
                            'amount'        => $balance_account,
                            'amount_bank'   => $api_amount_total,
                            'type'          => 'card_total_comparison',
                            'data_param'    => $error_data_param,
                            'ctime'         => getUtcTime()
                        ]);
                    }
                }
                $api_card_status    = $return_list['cardStatus'];
                $card_update_array  = ['balance' => $api_amount];
                $api_card_status_num = '';
                if($card_status != 3){ //用户已经删除的卡不能同步
                    if($api_card_status == 'A'){
                        $api_card_status_num = 1;
                    }else if($api_card_status == 'B'){
                        $api_card_status_num = 2;
                    }
                    if(!empty($api_card_status_num)){
                        $card_update_array += ['status' => $api_card_status_num];
                    }
                }
                $re = Db::name('cards')->where(['id' => $card_id])->update($card_update_array);
                if($re){
                    if(!empty($api_card_status_num)){
                        $logModel = new UserLog();
                        $logModel->setLog($user_id , 'update_card_status_api' , [
                            'card_num'      => $card_num ,
                            'old_status'    => $card_status,
                            'new_status'    => $api_card_status_num
                        ]);
                    }
                }
            }
        }
        $end_time   = getUtcTime();
        echo 'up card balance time : ' . ($end_time - $start_time) . PHP_EOL;

    }


    /**
     * 每半小时更新 从（当前日期-10天）至今的所有消费日志
     */
    public function upTranLog()
    {
        $update_time_all  = date("Y-m-d 00:00:00" , strtotime("-3 day"));
        $update_time_ymd  = date("Y-m-d",strtotime("-3 day"));

        $start_time = getUtcTime();
        Db::name('cards_trans')->where("ctime >= '" . $update_time_all . "' and bank_type !=3")->delete();
        $this->upTranLogAll('556305', $update_time_ymd, 1);
        $this->upTranLogAll('556766', $update_time_ymd, 1);
        $this->upTranLogAll('556766', $update_time_ymd, 2);
        $this->upTranLogAll('558068', $update_time_ymd, 1);
        $this->upTranLogAll('531847', $update_time_ymd, 1);
        $this->upTranLogAll('556735', $update_time_ymd, 1);

        $end_time   = getUtcTime();

        echo 'success time : ' . ($end_time - $start_time) ;
    }

    public function upTranLogAll($card_type , $update_time_ymd , $bank_type)
    {
        $create_card_param      = [
            "user_id"       => 1,
            "action_type"   => "search_trans",
            "card_type"     => $card_type,
            "bank_type"     => $bank_type,
            "post_param"  => [
                "startDate"    => $update_time_ymd,
            ]
        ];
        $request_api= PublicApi::requestApi("Comdata",$create_card_param);
        $blog       = $request_api['blog'] ?? false;
        if($blog){
            Db::startTrans();
            try {
                //获取退款记录最近的时间
                $credit_time=Db::name('cards_trans_credit')->order('ctime desc')->value('ctime');
                //获取所有卡的卡号
                $card_list = Db::name('cards')->select()->toArray();
                $card_array         = [];
                $userIdArray        = [];
                $cardStatusArray    = [];
                foreach ($card_list as $v_card){
                    $card_array[]                           = $v_card['card_num'];
                    $userIdArray[$v_card['card_num']]       = $v_card['user_id'];
                    $cardStatusArray[$v_card['card_num']]   = $v_card['status'];
                }
                $list = $request_api['list'];
                $history_status = ['Authorized','Posted','Declined','Credit'];
                foreach ($list as $k=>$v){
                    $cardNumber = $v['cardNumber'];
                    if(in_array($cardNumber , $card_array)){
                        $postedDate = $v['postedDate'] ?? '';
                        $utime      = !empty($postedDate) ? $v['postedDate'] . ' ' . $v['postedTime'] : '';
                        $shopping   = $v['acceptLocation'] ?? '';
                        $ctime      = $v['transactionDate'] . ' ' . $v['transactionTime'];
                        $reversalFlag = $v['reversalFlag'];
                        $current_status = $v['transactionStatus'];
                        $preAuthAmount  = $v['preAuthAmount'];
                        $idMatchNumber  = $v['idMatchNumber'] ?? '';
                        $correctiveAction = '';
                        if($v['transactionStatus'] == 'Declined'){
                            $correctiveAction = $v['correctiveAction'] ?? '';
                            if(empty($correctiveAction)){
                                $correctiveAction = $v['declineMessage'] ?? '';
                            }
                        }
                        $user_id  = $userIdArray[$cardNumber] ?? 0;

                        Db::name('cards_trans')->save([
                            'app_code'      => $v['approvalCode'],
                            'card_num'      => $cardNumber,
                            'user_id'       => $user_id,
                            'tran_status'   => $current_status,
                            'amount_auth'   => $preAuthAmount,
                            'amount_post'   => $v['postedAmount'],
                            'shopping'      => $shopping,
                            'desc'          => $correctiveAction,
                            'reversal_flag' => $reversalFlag,
                            'ctime'         => $ctime,
                            'utime'         => $v['transactionStatus'] == 'Declined' ? '' : $utime,
                            'bank_type'     => $bank_type
                        ]);
                        if($current_status == 'Credit' && !empty($idMatchNumber)) {
                            //只累加最新的Credit数据
                            $abs_amount = abs($v['postedAmount']);
                            $cardit_add = [
                                'card_num'      => $cardNumber,
                                'amount'        => $abs_amount,
                                'ctime'         => $ctime,
                                'idMatchNumber' => $idMatchNumber,
                                'user_id'       => $user_id,
                                'shopping'      => $shopping
                            ];
                            if ($card_type == '556766') {
                                $credit_list = Db::name('cards_trans_credit_cd')->where([
                                    'card_num' => $cardNumber,
                                    'idMatchNumber' => $idMatchNumber,
                                    'amount'    => $abs_amount
                                ])->find();
                                if(empty($credit_list)){
                                    $credit_result = CardsTransCredit::endCredit([
                                        'card_num'      =>  $cardNumber,
                                        'user_id'       =>  $user_id,
                                        'credit_amount' =>  $abs_amount,
                                        'shopping'      =>  $shopping,
                                    ] , 2);
                                    if($credit_result){
                                        $credit_server_set = UserSet::getCardSet($user_id);
                                        $credit_server_set_rate = $credit_server_set[$bank_type][$card_type]['rate_refund'];
                                        $credit_server_amount = getSprintf(round($abs_amount * $credit_server_set_rate,2));
                                        $cardit_add += [
                                            'credit_status' => 1,
                                            'utime' => getUtcTime(),
                                            'server_amount' => $credit_server_amount
                                        ];
                                    }
                                    Db::name('cards_trans_credit_cd')->save($cardit_add);
                                }
                            }else {
                                $credit_list = Db::name('cards_trans_credit')->where([
                                    'card_num' => $cardNumber,
                                    'idMatchNumber' => $idMatchNumber,
                                    'amount'    => $abs_amount
                                ])->find();
                                if(empty($credit_list)){
                                    Db::name('cards_trans_credit')->save($cardit_add);
                                }
                            }
                        }
                        if(!in_array($current_status,$history_status)){
                            $data_param = json_encode(['card_num'=>$cardNumber,'card_status'=>$current_status]);
                            if(!Db::name('api_error')->where(['data_param'=>$data_param])->find()){
                                Db::name('api_error')->save([
                                    'user_id'       => 0,
                                    'amount'        => $v['preAuthAmount'],
                                    'amount_bank'   => $v['preAuthAmount'],
                                    'type'          => 'card_total_comparison',
                                    'data_param'    => [''],
                                    'ctime'         => getUtcTime(),
                                    'is_rep'        => 1
                                ]);
                            }
                        }
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                $error_msg = $e->getMessage();
                var_dump($error_msg);
                Db::rollback();
            }
        }
    }

    public function upTranNewBank($i)
    {
        $type_array = [
            'authorization',
            'authorization.clearing',
            'authorization.reversal',
            'refund.authorization'
        ];
        $list = Db::name('cards')
            ->where(['bank_type'=>3])
            ->order('id asc')
            ->limit($i*50,50)
            ->select()->toArray();
        if($list){
            foreach ($list as $k=>$v){
                $user_id    = $v['user_id'];
                $card_num   = $v['card_num'];
                $card_token = $v['card_token'];
                $send_param         = [
                    "user_id"       => $user_id,
                    "card_num"      => $card_num,
                    "cardGuid"      => $card_token,
                    "action_type"   => "get_tran"
                ];
                $check_card_api = PublicApi::requestApi('Connexpay',$send_param);

                $return_blog_tran    = $check_card_api['blog'];
                $return_list_tran    = $check_card_api['list'];
                if($return_blog_tran){
                    if(isset($return_list_tran['transactions'])){
                        $transactions_list = array_reverse($return_list_tran['transactions']);
                        foreach ($transactions_list as $k_tran=>$v_tran){
                            $api_tran_status = $v_tran['status'];
                            $api_tran_type   = $v_tran['type'];
                            if($api_tran_status == "PENDING"){
                                if($api_tran_type == 'authorization'){
                                    $api_tran_status = 'Authorized';
                                }
                            }else if($api_tran_status == "DECLINED"){
                                $api_tran_status = 'Declined';
                            }else if($api_tran_status == "COMPLETION"){
                                if($api_tran_type == 'authorization.clearing'){
                                    $api_tran_status = 'Posted';
                                }else if($api_tran_type == 'refund.authorization.clearing'){
                                    $api_tran_status = 'Credit';
                                }
                            }else if($api_tran_status == "CLEARED"){
                                if($api_tran_type == 'authorization.reversal'){
                                    $api_tran_status = 'Reversal';
                                }else{
                                    continue;
                                }
                            }
                            $api_tran_amount = $v_tran['amount'];
                            $approvalCode    = $v_tran['approvalCode'] ?? '';
                            $api_tran_shop   = $v_tran['merchantName'] ?? '';
                            $correctiveAction= "";
                            $api_tran_ctime_real = substr(str_replace('T' , ' ' ,$v_tran['timestamp']) , 0 , -3);
                            $api_tran_ctime_CDT  = date('Y-m-d H:i:s',strtotime($api_tran_ctime_real . ' -5 hour'));
                            if(!empty($approvalCode)){
                                $current_tran_list = Db::name('cards_trans')->where([
                                    'app_code'=>$approvalCode,
                                    'bank_type'=>3
                                ])->find();
                                if($api_tran_status == 'Authorized'){
                                    if(empty($current_tran_list)){
                                        Db::name('cards_trans')->save([
                                            'user_id'       => $user_id,
                                            'app_code'      => $approvalCode,
                                            'card_num'      => $card_num,
                                            'tran_status'   => $api_tran_status,
                                            'amount_auth'   => $api_tran_amount,
                                            'reversal_flag' => 'N',
                                            'desc'          => $correctiveAction,
                                            'shopping'      => $api_tran_shop,
                                            'ctime'         => $api_tran_ctime_CDT,
                                            'ctime_real'    => $api_tran_ctime_real,
                                            'bank_type'     => 3
                                        ]);
                                    }
                                }else if($api_tran_status == 'Posted'){
                                    if($current_tran_list){
                                        $current_tran_id = $current_tran_list['id'];
                                        $tran_status     = $current_tran_list['tran_status'];
                                        if($tran_status == 'Authorized'){
                                            Db::name('cards_trans')->where(['id'=>$current_tran_id])->update([
                                                'tran_status'   => $api_tran_status,
                                                'amount_post'   => $api_tran_amount,
                                                'utime'         => $api_tran_ctime_CDT,
                                                'utime_real'    => $api_tran_ctime_real,
                                            ]);
                                        }
                                    }
                                }else if($api_tran_status == 'Credit'){
                                    if($current_tran_list){
                                        $current_tran_id = $current_tran_list['id'];
                                        $tran_status     = $current_tran_list['tran_status'];
                                        if($tran_status == 'Authorized'){
                                            Db::name('cards_trans')->where(['id'=>$current_tran_id])->update([
                                                'tran_status'   => $api_tran_status,
                                                'amount_post'   => $api_tran_amount,
                                                'utime'         => $api_tran_ctime_CDT,
                                                'utime_real'    => $api_tran_ctime_real,
                                            ]);
                                        }
                                    }else{
                                        Db::name('cards_trans')->save([
                                            'user_id'       => $user_id,
                                            'app_code'      => $approvalCode,
                                            'card_num'      => $card_num,
                                            'tran_status'   => $api_tran_status,
                                            'amount_auth'   => $api_tran_amount,
                                            'reversal_flag' => 'N',
                                            'desc'          => $correctiveAction,
                                            'shopping'      => $api_tran_shop,
                                            'ctime'         => $api_tran_ctime_CDT,
                                            'ctime_real'    => $api_tran_ctime_real,
                                            'amount_post'   => $api_tran_amount,
                                            'utime'         => $api_tran_ctime_CDT,
                                            'utime_real'    => $api_tran_ctime_real,
                                            'bank_type'     => 3
                                        ]);
                                    }
                                }
                            }else{
                                $current_tran_list = Db::name('cards_trans')->where([
                                    'ctime_real'=>$api_tran_ctime_CDT,
                                    'bank_type'=>3
                                ])->find();
                                if(empty($current_tran_list)){
                                    $save_param = [
                                        'user_id'       => $user_id,
                                        'app_code'      => $approvalCode,
                                        'card_num'      => $card_num,
                                        'tran_status'   => $api_tran_status,
                                        'amount_auth'   => $api_tran_amount,
                                        'reversal_flag' => 'N',
                                        'shopping'      => $api_tran_shop,
                                        'ctime'         => $api_tran_ctime_CDT,
                                        'ctime_real'    => $api_tran_ctime_real,
                                        'bank_type'     => 3
                                    ];
                                    if($api_tran_status == 'Declined'){
                                        $correctiveAction = $v_tran['description'] ?? '';
                                    }else if($api_tran_status == 'Credit'){
                                        $save_param += [
                                            'amount_post'   => $api_tran_amount,
                                            'utime'         => $api_tran_ctime_CDT,
                                            'utime_real'    => $api_tran_ctime_real
                                        ];
                                    }
                                    $save_param += [
                                        'desc'          => $correctiveAction
                                    ];
                                    Db::name('cards_trans')->save($save_param);
                                }
                            }
                        }
                    }
                }
            }
        }


    }

    public function upCvv()
    {
        $list = Db::name('cards')->where("cvv='' and bank_type=1")->select()->toArray();
        if($list){
            foreach ($list as $k=>$v){
                $card_id = $v['id'];
                $exp_date= $v['exp_date'];
                $user_id = $v['user_id'];
                $card_type = $v['card_type'];
                $bank_type = $v['bank_type'];
                $card_num  = $v['card_num'];
                if(empty($exp_date)){
                    continue;
                }
                //查询Cvv
                $searchCvvParam =[
                    "user_id"       => $user_id,
                    "action_type"   => "searchCvv",
                    "card_type"     => $card_type,
                    "bank_type"     => $bank_type,
                    "post_param"  => [
                        "card_num"  => $card_num,
                        "exp_date"  => $exp_date
                    ]
                ];
                $searchCvvApi = PublicApi::requestApi('Comdata3',$searchCvvParam);
                $search_cvv_blog  = $searchCvvApi['blog'];
                $search_cvv_list  = $searchCvvApi['list'];
                if($search_cvv_blog){
                    $cvv = $search_cvv_list['cardSecurityCode'] ?? '';
                    if(!empty($cvv)){
                        $up_cvv = [
                            'cvv'           => $cvv ,
                            'check_status'  => 1 ,  //1=已开卡,
                            'utime'         => getUtcTime()
                        ];
                        echo $card_num . '---' . $cvv . '<br>';
                        Db::name('cards')->where(['id'=>$card_id])->update($up_cvv);
                    }
                }
            }
        }
    }

    /**
     * 每半小时更新 从（当前日期-10天）至今的所有消费日志
     */
    public function upTranLogCredit()
    {
        exit;
//        $create_card_param      = [
//            "user_id"       => 1,
//            "action_type"   => "search_trans",
//            "post_param"  => [
//                "startDate"    => '2022-09-15',
//            ]
//        ];
        $request_api= PublicApi::requestApi("Comdata",$create_card_param);
        $blog       = $request_api['blog'] ?? false;
        if($blog){

            $card_list = Db::name('cards')->where('user_id != 1')->field('card_num')->select()->toArray();
            $card_array= [];
            foreach ($card_list as $v_card){
                $card_array[] = $v_card['card_num'];
            }
            $list = $request_api['list'];
            foreach ($list as $k=>$v){
                $cardNumber = $v['cardNumber'];
                if(in_array($cardNumber , $card_array)){
                    $shopping   = $v['acceptLocation'] ?? '';
                    if($v['transactionStatus'] == 'Credit'){
                        Db::name('cards_trans_credit')->save([
                            'card_num'      => $cardNumber,
                            'tran_status'   => $v['transactionStatus'],
                            'amount'        => abs($v['preAuthAmount']),
                            'shopping'      => $shopping,
                            'ctime'         => $v['transactionDate'] . ' ' . $v['transactionTime'],
                        ]);
                    }
                }
            }
        }
        echo 'success';
    }

    public function upErrorCredit()
    {
        $time = date("Y-m-d",strtotime("-1 day"));
        $list_time = $time;
        $list = Db::name('api_accept_lss')
            ->where("eventType = 'purchase.card.return.auth.settled' 
            and (ctime between '{$list_time} 00:00:00' and '{$list_time} 23:59:59')")
            ->select()->toArray();
        $aa = [];
        foreach ($list as $k=>$v){
            $card_num       = $v['card_num'];
            $tran_guid      = $v['tran_guid'];
            $user_id        = $v['user_id'];
            $approvalCode       = $v['app_code'];
            $ctime          = $v['ctime'];
            $ctime_real     = $v['eventTime'];
            $amount         = $v['amount'];
            $json_data      = json_decode($v['json_data'] , true);
            $api_tran_shop   = $json_data['data']['merchantName'] ?? '';
            //判断消费日志是否漏掉
            $current_tran_list = Db::name('cards_trans')->where([
                'tran_token'    =>  $tran_guid,
                'card_num'      =>  $card_num,
            ])->find();
            if(empty($current_tran_list)){
                $insert_credit = [
                    'user_id'       => $user_id,
                    'app_code'      => $approvalCode,
                    'card_num'      => $card_num,
                    'tran_status'   => "Credit",
                    'amount_auth'   => $amount,
                    'reversal_flag' => 'N',
                    'shopping'      => $api_tran_shop,
                    'ctime'         => $ctime,
                    'ctime_real'    => $ctime_real,
                    'amount_post'   => $amount,
                    'utime'         => $ctime,
                    'utime_real'    => $ctime_real,
                    'bank_type'     => 3,
                    'tran_token'    => $tran_guid
                ];
                Db::name('cards_trans')->save($insert_credit);
            }
            //判断扣款
            $abs_amount = abs($amount);
            $check_credit = Db::name('cards_trans_credit_lss')->where([
                'card_num'      => $card_num,
                'tran_token'    =>  $tran_guid,
            ])->where("ctime > '2024-01-01 00:00:00'")->find();
            if(empty($check_credit)){
//                $aa[] = $tran_guid;
                $card_status = Db::name('cards')->where(['card_num'=>$card_num])->value('status');
                $credit_result = CardsTransCredit::endCredit([
                    'card_num'      =>  $card_num,
                    'user_id'       =>  $user_id,
                    'credit_amount' =>  $abs_amount,
                    'shopping'      =>  $api_tran_shop,
                ] , 2);
                $cardit_add = [
                    'card_num'      => $card_num,
                    'amount'        => $abs_amount,
                    'ctime'         => $ctime,
                    'app_code'      => $approvalCode,
                    'user_id'       => $user_id,
                    'shopping'      => $api_tran_shop,
                    'tran_token'    => $tran_guid,
                    'card_status'   => $card_status
                ];
                if($credit_result){
                    $credit_server_set = UserSet::getCardSet($user_id);
                    $card_type         = substr($card_num , 0,6);
                    $credit_server_set_rate = $credit_server_set[3][$card_type]['rate_refund'];
                    $credit_server_amount = getSprintf(round($abs_amount * $credit_server_set_rate,2));
                    $cardit_add += [
                        'credit_status' => 1,
                        'utime' => getUtcTime(),
                        'server_amount' => $credit_server_amount
                    ];
                }
                Db::name('cards_trans_credit_lss')->save($cardit_add);
            }
        }
        echo 'xfcredit' . '---' . $list_time . "---" ;
    }


    public function iceUser()
    {
        $list = Db::name('user_data')->alias('ud')
            ->leftJoin('user u' , 'u.id=ud.user_id')
            ->field('u.id,u.status,u.username,ud.tran_declined_amount,ud.declined_tran_count')
            ->select()->toArray();
        $default_declined_amount = getSetting('declined_amount');
        $default_declined_rate   = getSetting('declined_rate');
        $i = '';
        foreach ($list as $k=>$v){
            $declined_amount= $v['tran_declined_amount'];
            $declined_rate  = $v['declined_tran_count'];
            $status         = $v['status'];
            $user_id        = $v['id'];
            $username       = $v['username'];
            if($status == 1){
                if(($declined_amount - $default_declined_amount) >= 0 &&
                    ($declined_rate - $default_declined_rate) >= 0){
                    Db::name('user')->where(['id'=>$user_id])->update(['status'=>2]);
                    EmailSend::sendGridEmail('debt_month' , [
                        'email'     => $username,
                        'title'     => "{$username} , 您好 , 您的账号拒付率过高! 已停用 ,请联系管理员.",
                    ]);
                    $i .= $username . ' , ';
                }
            }
        }
        echo $i . ' ---- success';
    }

    public function iceKeyChao()
    {
        $list = Db::name('user_ice_log')
            ->where(['is_ok' => 0])
            ->order('id asc')
            ->limit(10)->select()->toArray();
        $ctime = getUtcTime();
        $unUser         = getSetting('amount_post_limit_user');
        $unUserArray    = explode(',' , $unUser);
        foreach ($list as $k=>$v){
            $ice_id  = $v['id'];
            $user_id = $v['user_id'];
            $type    = $v['type'];
            $key_name= $v['key_name'];
            $amount_auth = $v['amount_auth'];
            $amount_post = $v['amount_post'];
            $api_type= $v['api_type'];
            $card_num = $v['card_num'];
            $db_ctime = $v['ctime'];

            //豁免用户处理
            if(!in_array($user_id,$unUserArray)){
                $user_list  = Db::name('user')->where(['id'=>$user_id])->find();
                $username   = $user_list['username'];
                $user_status= $user_list['status'];

                if($user_status == 1){
                    if($type == 1){
                        $title = "超额({$amount_auth}:{$amount_post})";
                        //结算金额小于10豁免处理
                        if($amount_post - 10 >0){
                            self::iceKeyChaoDetail($username ,$user_id,$ice_id,$title,$card_num);
                        }else{
                            Db::name('user_ice_log')->where(['id'=>$ice_id])->update([
                                'is_ok' => 1,
                                'result'=> '结算金额小于10豁免处理',
                                'utime' => $ctime
                            ]);
                        }
                    }else if($type == 2){//预扣超额
                        $title = "预扣超额";
                        self::iceKeyAuthChaoDetail($username ,$user_id,$ice_id,$title , $card_num , $db_ctime);
                    }else{
                        $title = "违规关键字({$key_name})";
                        if($key_name == 'google_1.95'){
                            EmailSend::sendGridEmail('ice_user' , [
                                'email'     => "897194@gmail.com",
                                'body'      => "管理员您好，账号:{$username}<br /><br />
                                    名下卡号:{$card_num},有$ 1.95的消费<br /><br />
                                    vvacard运营小组<br />",
                                'title'     => "账户冻结通知(1.95) - {$title} -- CardEcho",
                            ]);
                            EmailSend::sendGridEmail('ice_user' , [
                                'email'     => "sensir267@gmail.com",
                                'body'      => "管理员您好，账号:{$username}<br /><br />
                                    名下卡号:{$card_num},有$ 1.95的消费<br /><br />
                                    vvacard运营小组<br />",
                                'title'     => "账户冻结通知(1.95) - {$title} -- CardEcho",
                            ]);
                            Db::name('user_ice_log')->where(['id'=>$ice_id])->update([
                                'is_ok' => 1,
                                'result'=> '$1.95消费已通知',
                                'utime' => $ctime
                            ]);
                        }else{
                            self::iceKeyChaoDetail($username ,$user_id,$ice_id,$title , $card_num);
                        }
                    }
                }else{
                    Db::name('user_ice_log')->where(['id'=>$ice_id])->update([
                        'is_ok' => 1,
                        'result'=> '重复处理',
                        'utime' => $ctime
                    ]);
                }
            }else{
                Db::name('user_ice_log')->where(['id'=>$ice_id])->update([
                    'is_ok' => 1,
                    'result'=> '豁免用户处理',
                    'utime' => $ctime
                ]);
            }
        }
    }

    public static function iceKeyChaoDetail($username ,$user_id,$ice_id,$title,$card_num)
    {
        $ctime = getUtcTime();
        Db::name('user')->where(['id'=>$user_id])->update(['status'=>2]);

        //is_ok=2 ,说明只冻结了用户
        Db::name('user_ice_log')->where(['id'=>$ice_id])->update([
            'is_ok' => 2,
            'result'=> json_encode(['username'=>$username]),
            'utime' => $ctime
        ]);

        //冻结名下所有卡
        $card_list  = Db::name('cards')
            ->where("is_del !=1 
            and is_action =0 
            and status=1 
            and user_id={$user_id}
            and card_num={$card_num}")
            ->select()->toArray();
        $success_card = 0;
        $success_card_num =[];
        if(!empty($card_list)){
            foreach ($card_list as $k_card=>$v_card){
                $card_id        = $v_card['id'];
                $card_type      = $v_card['card_type'];
                $bank_type      = $v_card['bank_type'];
                $card_num       = $v_card['card_num'];
                $card_token     = $v_card['card_token'];
                $type_api       = 'card_suspended';
                $change_status  = "2";

                if($bank_type == 3){
                    $data       = [
                        "user_id"       => $user_id,
                        "action_type"   => $type_api,
                        "cardGuid"      => $card_token,
                        "card_num"      => $card_num,
                        "request_data"  => [
                            "Activated" => false
                        ]
                    ];
                    $company_name = 'Connexpay';
                }else{
                    $data       = [
                        "user_id"       => $user_id,
                        "action_type"   => $type_api,
                        "card_type"     => $card_type,
                        "bank_type"     => $bank_type,
                        "post_param"    => [
                            "card_num"       => $card_num
                        ]
                    ];
                    $company_name = 'Comdata';
                }
                $update_result = PublicApi::requestApi($company_name , $data);
                $update_result_blog = $update_result['blog'];
                if($update_result_blog){
                    $update_where = [
                        'status'=>  $change_status,
                        'utime' =>  getUtcTime()
                    ];
                    //更新卡列表状态
                    Db::name('cards')->where(['id'=> $card_id])->update($update_where);
                    $success_card_num[] = $card_num;
                    $success_card += 1;
                }
            }
        }

        //如果上面冻结卡都没失败 is_ok=1
        $re = Db::name('user_ice_log')->where(['id'=>$ice_id])->update([
            'is_ok' => 1,
            'result'=> json_encode([
                'username'=>$username,
                'card_num'=>$success_card_num
            ]),
            'utime' => $ctime
        ]);
        $success_card_num_json = json_encode($success_card_num);
        if($re){
            EmailSend::sendGridEmail('ice_user' , [
                'email'     => "897194@gmail.com",
                'body'      => "管理员您好，冻结账号:{$username}<br /><br />
                                    冻结名下卡号:{$success_card_num_json}<br /><br />
                                    vvacard运营小组<br />",
                'title'     => "账户冻结通知 - {$title} -- CardEcho",
            ]);
            EmailSend::sendGridEmail('ice_user' , [
                'email'     => "sensir267@gmail.com",
                'body'      => "管理员您好，冻结账号:{$username}<br /><br />
                                    冻结名下卡号:{$success_card_num_json}<br /><br />
                                    vvacard运营小组<br />",
                'title'     => "账户冻结通知 - {$title} -- CardEcho",
            ]);
        }

        Db::name('manage_log')->save([
            'manage_id' => 1,
            'desc'      => 'tran_ice_key_del',
            'content'   => json_encode([
                'card_num' => $success_card_num,
                'username' => $username
            ]),
            'ip'        => ip(),
            'ctime'     => $ctime
        ]);
    }

    public static function iceKeyAuthChaoDetail($username ,$user_id,$ice_id,$title,$card_num , $db_ctime)
    {
        $ctime = getUtcTime();
        $end_time = $db_ctime - 24*60*60;
        $tran_auth_amount_sum = Db::name('cards_trans')
            ->where("UNIX_TIMESTAMP(ctime) >= {$end_time} and tran_status='Authorized' and user_id={$user_id}")
            ->sum('amount_auth');
        $monitor_tran_auth_amount_all = getSetting('monitor_tran_auth_amount_all');
        //统计这个用户24小时内的预授权总金额，如果总金额大于、等于N
        if($tran_auth_amount_sum - $monitor_tran_auth_amount_all >=0){
            Db::name('user')->where(['id'=>$user_id])->update(['status'=>2]);
            //is_ok=2 ,说明只冻结了用户
            Db::name('user_ice_log')->where(['id'=>$ice_id])->update([
                'is_ok' => 2,
                'result'=> json_encode(['username'=>$username]),
                'utime' => $ctime
            ]);
            //冻结名下所有卡
            $card_list  = Db::name('cards')
                ->where("is_del !=1 
            and is_action =0 
            and status=1 
            and user_id={$user_id}
            and card_num={$card_num}")
                ->select()->toArray();
            $success_card = 0;
            $success_card_num =[];
            if(!empty($card_list)){
                foreach ($card_list as $k_card=>$v_card){
                    $card_id        = $v_card['id'];
                    $card_type      = $v_card['card_type'];
                    $bank_type      = $v_card['bank_type'];
                    $card_num       = $v_card['card_num'];
                    $card_token     = $v_card['card_token'];
                    $type_api       = 'card_suspended';
                    $change_status  = "2";

                    if($bank_type == 3){
                        $data       = [
                            "user_id"       => $user_id,
                            "action_type"   => $type_api,
                            "cardGuid"      => $card_token,
                            "card_num"      => $card_num,
                            "request_data"  => [
                                "Activated" => false
                            ]
                        ];
                        $company_name = 'Connexpay';
                    }else{
                        $data       = [
                            "user_id"       => $user_id,
                            "action_type"   => $type_api,
                            "card_type"     => $card_type,
                            "bank_type"     => $bank_type,
                            "post_param"    => [
                                "card_num"       => $card_num
                            ]
                        ];
                        $company_name = 'Comdata';
                    }
                    $update_result = PublicApi::requestApi($company_name , $data);
                    $update_result_blog = $update_result['blog'];
                    if($update_result_blog){
                        $update_where = [
                            'status'=>  $change_status,
                            'utime' =>  getUtcTime()
                        ];
                        //更新卡列表状态
                        Db::name('cards')->where(['id'=> $card_id])->update($update_where);
                        $success_card_num[] = $card_num;
                        $success_card += 1;
                    }
                }
            }

            //如果上面冻结卡都没失败 is_ok=1
            $re = Db::name('user_ice_log')->where(['id'=>$ice_id])->update([
                'is_ok' => 1,
                'result'=> json_encode([
                    'auth_amount_all'=>$tran_auth_amount_sum,
                    'card_num'=>$success_card_num,
                ]),
                'utime' => $ctime
            ]);
            $success_card_num_json = json_encode($success_card_num);
            if($re){
                $title .= "24小时预扣总金额({$tran_auth_amount_sum}),已超额";
                EmailSend::sendGridEmail('ice_user' , [
                    'email'     => "sensir267@gmail.com",
                    'body'      => "管理员您好，冻结账号:{$username}<br /><br />
                                    冻结名下卡号:{$success_card_num_json}<br /><br />
                                    24小时预扣总金额({$tran_auth_amount_sum}),已超额<br /><br />
                                    vvacard运营小组<br />",
                    'title'     => "账户冻结通知 - {$title} -- CardEcho",
                ]);
                EmailSend::sendGridEmail('ice_user' , [
                    'email'     => "897194@gmail.com",
                    'body'      => "管理员您好，冻结账号:{$username}<br /><br />
                                    冻结名下卡号:{$success_card_num_json}<br /><br />
                                    24小时预扣总金额({$tran_auth_amount_sum}),已超额<br /><br />
                                    vvacard运营小组<br />",
                    'title'     => "账户冻结通知 - {$title} -- CardEcho",
                ]);
            }

            Db::name('manage_log')->save([
                'manage_id' => 1,
                'desc'      => 'tran_ice_key_del',
                'content'   => json_encode([
                    'card_num' => $success_card_num,
                    'username' => $username
                ]),
                'ip'        => ip(),
                'ctime'     => $ctime
            ]);
        }else{
            Db::name('user_ice_log')->where(['id'=>$ice_id])->update([
                'is_ok' => 1,
                'result'=> "24小时预扣总金额({$tran_auth_amount_sum}),未超额,不进行冻结处理",
                'utime' => $ctime
            ]);
        }
    }

    public function test()
    {
        $update_time_all  = date("Y-m-d 00:00:00" , strtotime("-10 day"));
        $update_time_ymd  = date("Y-m-d",strtotime("-10 day"));

        $create_card_param      = [
            "user_id"       => 1,
            "action_type"   => "search_trans",
            "card_type"     => '556766',
            "post_param"  => [
                "startDate"    => $update_time_ymd,
            ]
        ];
        $request_api= PublicApi::requestApi("Comdata",$create_card_param);
        $list = [];
        foreach ($request_api['list'] as $k=>$v){
            if($v['transactionStatus'] == 'Declined'){
                $list[] = $v;
            }
        }
        dd(array_reverse($list));
        exit;
    }

    //处理负值的卡
    public function upDetAmountCard()
    {
        try {
            $card_list = Db::name('cards')->where("balance < 0")->select()->toArray();
            if($card_list){
                $cache_key = 'up_det_amount_card';
                $i = 0;
                foreach ($card_list as $k=>$v){
                    $card_id = $v['id'];
                    cardsModel::checkCardBalanceApi($card_id);
                    $card_list_new = Db::name('cards')->where(['id'=>$card_id])->select()->toArray();
                    $cardModel = new cardsModel();
                    $re = $cardModel->repairCard($card_list_new, $cache_key);
                    if($re >0){
                        $i++;
                    }
                }
                echo $i;
            }
        }catch (\Exception $e){
            var_dump($e->getMessage());
        }
    }

    public function upHomeData(){
        $start = getUtcTime();
        UserCashLog::getHomeData(['is_all_up' => 1]);
        $end   = getUtcTime();
        echo 'success time : ' . ($end - $start) ;
    }

    public function upHomeDataOne(){
        $start = getUtcTime();
        UserCashLog::getHomeDataOne();
        $end   = getUtcTime();
        echo 'success time : ' . ($end - $start) ;
    }

    public function serverLss()
    {
        //拒付阈值,超过阈值管理员处理
        $declined_max_amount = getSetting('declined_max_amount');
        $lss_list = Db::name('server_lss')
            ->where("is_action = 0 and tran_amount <= {$declined_max_amount}")
            ->order('id asc')
            ->limit(10)->select()->toArray();
        if($lss_list){
            foreach ($lss_list as $k=>$v){
                Db::startTrans();
                try {
                    $lss_id     = $v['id'];
                    $user_id    = $v['user_id'];
                    $amount     = $v['server_amount'];
                    $card_num   = $v['card_num'];
                    $cl_ctime   = getUtcTime();
                    $type       = $v['type'];

                    $user_list      = Db::name('user')->where(['id'=>$user_id])->find();
                    $user_balance       = $user_list['balance'];
                    $user_balance_end   = $user_balance - $amount;
                    $card_num64 = substr($card_num , 0 ,6) . '***' . substr($card_num , -4);
                    if($type == 0){
                        $desc = "0验证服务费({$card_num64})";
                    }else{
                        $desc = "拒付服务费{{$card_num64}}";
                    }

                    Db::name('user')->where(['id'=>$user_id])->update(['balance'=>$user_balance_end]);

                    Db::name('user_cash_log')->save([
                        'user_id'       => $user_id,
                        'type'          => 1,
                        'action_type'   => 3,
                        'card_type'     => substr($card_num , 0 ,6),
                        'amount'        => $amount,
                        'balance'       => $user_balance_end,
                        'desc'          => $desc,
                        'ctime'         => $cl_ctime,
                        'bank'          => 2
                    ]);
                    Db::name('server_lss')->where(['id'=>$lss_id])
                        ->update([
                            'is_action'=> 1,
                            'cl_ctime' => $cl_ctime
                        ]);

                    Db::commit();
                } catch (\Exception $e) {
                    $error_msg = $e->getMessage();
                    echo $error_msg;
                    Db::rollback();
                }
            }
        }
    }

    public function serverCd()
    {
        //拒付阈值,超过阈值管理员处理
        $declined_max_amount = getSetting('declined_max_amount');
        $lss_list = Db::name('server_cd')
            ->where("is_action = 0 and tran_amount <= {$declined_max_amount}")
            ->order('id asc')
            ->limit(10)->select()->toArray();
        if($lss_list){
            foreach ($lss_list as $k=>$v){
                Db::startTrans();
                try {
                    $lss_id     = $v['id'];
                    $user_id    = $v['user_id'];
                    $amount     = $v['server_amount'];
                    $card_num   = $v['card_num'];
                    $cl_ctime   = getUtcTime();
                    $type       = $v['type'];

                    $user_list      = Db::name('user')->where(['id'=>$user_id])->find();
                    $user_balance       = $user_list['balance'];
                    $user_balance_end   = $user_balance - $amount;
                    $card_num64 = substr($card_num , 0 ,6) . '***' . substr($card_num , -4);
                    if($type == 0){
                        $desc = "0验证服务费({$card_num64})";
                    }else{
                        $desc = "拒付服务费{{$card_num64}}";
                    }

                    Db::name('user')->where(['id'=>$user_id])->update(['balance'=>$user_balance_end]);

                    Db::name('user_cash_log')->save([
                        'user_id'       => $user_id,
                        'type'          => 1,
                        'action_type'   => 3,
                        'card_type'     => substr($card_num , 0 ,6),
                        'amount'        => $amount,
                        'balance'       => $user_balance_end,
                        'desc'          => $desc,
                        'ctime'         => $cl_ctime,
                        'bank'          => 1
                    ]);
                    Db::name('server_cd')->where(['id'=>$lss_id])
                        ->update([
                            'is_action'=>1,
                            'cl_ctime' => $cl_ctime
                            ]);

                    Db::commit();
                } catch (\Exception $e) {
                    $error_msg = $e->getMessage();
                    echo $error_msg;
                    Db::rollback();
                }
            }
        }
    }
    public function codeLss()
    {
        //拒付阈值,超过阈值管理员处理
        $declined_max_amount = getSetting('declined_max_amount');
        $lss_list = Db::name('code_log')
            ->where(['is_action' => 0])
            ->order('id asc')
            ->limit(10)->select()->toArray();
        if($lss_list){
            foreach ($lss_list as $k=>$v){
                Db::startTrans();
                try {
                    $lss_id     = $v['id'];
                    $user_id    = $v['user_id'];
                    $amount     = $v['amount'];
                    $card_num   = $v['card_num'];
                    $cl_ctime   = getUtcTime();

                    $user_list          = Db::name('user')->where(['id'=>$user_id])->find();
                    $user_balance       = $user_list['balance'];
                    $user_balance_end   = getSprintf($user_balance - $amount);
                    $card_num64         = substr($card_num , 0 ,6) . '***' . substr($card_num , -4);
                    $desc               = "货币转换费({$card_num64})";

                    Db::name('user')->where(['id'=>$user_id])->update(['balance'=>$user_balance_end]);

                    Db::name('user_cash_log')->save([
                        'user_id'       => $user_id,
                        'type'          => 1,
                        'action_type'   => 3,
                        'card_type'     => substr($card_num , 0 ,6),
                        'amount'        => $amount,
                        'balance'       => $user_balance_end,
                        'desc'          => $desc,
                        'ctime'         => $cl_ctime,
                        'bank'          => 2
                    ]);

                    Db::name('code_log')->where(['id'=>$lss_id])
                        ->update([
                            'is_action'=> 1,
                            'cl_ctime' => $cl_ctime
                            ]);

                    Db::commit();
                } catch (\Exception $e) {
                    $error_msg = $e->getMessage();
                    echo $error_msg;
                    Db::rollback();
                }
            }
        }
    }

    public function userIce()
    {
        $user_ice_limit = getSetting('user_ice_limit');
        $user_list = Db::name('user')->where("balance <= {$user_ice_limit} and status = 1")->select()->toArray();
        $username_array = [];
        if(!empty($user_list)){
            foreach ($user_list as $k=>$v){
                $user_id = $v['id'];
                $username= $v['username'];
                $card_list = Db::name('cards')
                    ->where(['user_id'=>$user_id,'status'=>1])->select()->toArray();
                $time               = getUtcTime();
                $success_card_num   = [];
                if(!empty($card_list)){
                    foreach ($card_list as $k_card=>$v_card){
                        $card_id        = $v_card['id'];
                        $card_type      = $v_card['card_type'];
                        $bank_type      = $v_card['bank_type'];
                        $card_num       = $v_card['card_num'];
                        $card_token     = $v_card['card_token'];
                        $type_api       = 'card_suspended';
                        $change_status  = "2";

                        if($bank_type == 3){
                            $data       = [
                                "user_id"       => $user_id,
                                "action_type"   => $type_api,
                                "cardGuid"      => $card_token,
                                "card_num"      => $card_num,
                                "request_data"  => [
                                    "Activated" => false
                                ]
                            ];
                            $company_name = 'Connexpay';
                        }else{
                            $data       = [
                                "user_id"       => $user_id,
                                "action_type"   => $type_api,
                                "card_type"     => $card_type,
                                "bank_type"     => $bank_type,
                                "post_param"    => [
                                    "card_num"       => $card_num
                                ]
                            ];
                            $company_name = 'Comdata';
                        }
                        $update_result = PublicApi::requestApi($company_name , $data);
                        $update_result_blog = $update_result['blog'];
                        if($update_result_blog){
                            $update_where = [
                                'status'=>  $change_status,
                                'utime' =>  $time
                            ];
                            //更新卡列表状态
                            Db::name('cards')->where(['id'=> $card_id])->update($update_where);
                            $success_card_num[] = $card_num;
                        }
                    }
                }
                $username_array[] = [
                    'username' => $username,
                    'card_num' => $success_card_num
                ];
                $re = Db::name('user')->where(['id'=>$user_id])->update(['status'=>2]);
                if($re){
                    ManageLog::saveManageLog([
                        'manage_id' => 0,
                        'desc'      => 'user_ice-100',
                        'time'      => getUtcTime(),
                        'content'   => json_encode([
                            'card_num' => $success_card_num,
                            'username' => $username
                        ])
                    ]);
                }
            }
        }
        if(!empty($username_array)){
            echo json_encode($username_array);
        }else{
            echo 'no user';
        }
    }
}